package com.hj.controller;

import com.hj.domain.Girl;
import com.hj.domain.Result;
import com.hj.properties.GirlProperties;
import com.hj.repository.GirlRepository;
import com.hj.service.GirlService;
import com.hj.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Administer on 2017/6/18.
 */
@RestController
public class GirlController {

    private final static Logger logger= LoggerFactory.getLogger(GirlController.class);
    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    @Autowired
    private GirlProperties girlProperties;

    @GetMapping(value = "/hi")
    public String hello() {
        return girlProperties.getCupSize();
    }
    //添加一个女生
    @PostMapping(value = "/girls")
    public Result<Girl> addGirl(@Valid Girl girl, BindingResult bindingResult){
        if(bindingResult.hasErrors()) {
            //System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());

        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());
        return ResultUtil.success(girlRepository.save(girl));
    }

    //查询所有
    @GetMapping(value = "/girls")
    public List<Girl> findAll() {
        logger.info("111222");
        return girlRepository.findAll();
    }

    @PostMapping(value = "/girls/age/{age}")
    public List<Girl> findByAge(@PathVariable(value = "age") Integer age) {
        return girlRepository.findByAge(age);
    }

    //修改女生
    @PostMapping(value = "/girls/{id}")
    public Girl updateGirl(@PathVariable("id") Integer id,
                             @RequestParam("cupSize") String cupSize,
                             @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setAge(age);
        girl.setId(id);
        girl.setCupSize(cupSize);
        return girlRepository.save(girl);
    }

    //删除女生
    @PostMapping(value = "girls/delete/{id}")
    public void deleteGirl(@PathVariable("id") Integer id){
        Girl girl=new Girl();
        girl.setId(id);
        girlRepository.delete(girl);
    }

    //事务管理
    @PostMapping(value = "girls/insert")
    public void insertTwo(){
        girlService.insertTwo();
    }

    @GetMapping(value = "girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
        girlService.getAge(id);
    }
}
